package com.github.operationlog.command;

import com.github.operationlog.MethodAttribute;
import com.github.operationlog.output.OperationLogOutput;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;

@Slf4j
public class UpdateOperationCommand extends OperationCommand {
    public UpdateOperationCommand(String table, Object target, MethodAttribute methodAttribute,
                                  Method findByIdMethod, OperationLogOutput operationLogOutput) {
        super(table, target, methodAttribute, findByIdMethod, operationLogOutput);
    }

    @Override
    public Object execute0(Object target, Method method, Object[] args, Object entityId) {
        if (entityId == null) {
            log.warn("实体更新方法记录日志失败，原因：实体ID为空，updateMethod={}#{}",
                    methodAttribute.getTargetName(), method.getName());
            return ReflectionUtils.invokeMethod(method, target, args);
        }

        Object oldEntity = findById(entityId);
        if (oldEntity == null) {
            log.warn("实体更新方法记录日志失败，原因：根据实体ID未查询到旧实体，updateMethod={}#{}, entityId={}",
                    methodAttribute.getTargetName(), method.getName(), methodAttribute.getTargetName(), entityId);
            return ReflectionUtils.invokeMethod(method, target, args);
        }

        // 执行业务更新方法
        Object returnValue = ReflectionUtils.invokeMethod(method, target, args);

        Object newEntity = methodAttribute.isEntityParam() ? args[0] : findById(entityId);
        insertLog(entityId, oldEntity, newEntity);
        return returnValue;
    }
}